package com.huishu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huishu.commons.pojo.Result;
import com.huishu.commons.utlis.BeanUtils;
import com.huishu.user.mapper.UserReceiveAddressMapper;
import com.huishu.user.pojo.dto.UserReceiveAddressDTO;
import com.huishu.user.pojo.model.UserReceiveAddressDO;
import com.huishu.user.service.UserReceiveAddressService;
import com.huishu.user.utils.AssistantContext;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author generator@ljj
 * @since 2023-04-12
 */
@Service
public class UserReceiveAddressServiceImpl extends ServiceImpl<UserReceiveAddressMapper, UserReceiveAddressDO> implements UserReceiveAddressService {

    @Override
    public Result addOrUpdate(UserReceiveAddressDTO userReceiveAddressDTO) {
        userReceiveAddressDTO.setUserId(AssistantContext.getCurrentUid());
        if(userReceiveAddressDTO.getIsDefault()){
            LambdaUpdateWrapper<UserReceiveAddressDO> uw = Wrappers.lambdaUpdate(UserReceiveAddressDO.class)
                    .set(UserReceiveAddressDO::getIsDefault,false)
                    .eq(UserReceiveAddressDO::getUserId,AssistantContext.getCurrentUid());
            this.update(uw);
            UserReceiveAddressDO userReceiveAddressDO = BeanUtils.copyProperties(userReceiveAddressDTO, UserReceiveAddressDO.class);
            this.saveOrUpdate(userReceiveAddressDO);
            return Result.success();
        }
        UserReceiveAddressDO userReceiveAddressDO = BeanUtils.copyProperties(userReceiveAddressDTO, UserReceiveAddressDO.class);
        this.saveOrUpdate(userReceiveAddressDO);
        return Result.success();
    }

    @Override
    public Result findAll(Long currentUid) {
        LambdaQueryWrapper<UserReceiveAddressDO> queryWrapper = Wrappers.lambdaQuery(UserReceiveAddressDO.class)
                .eq(UserReceiveAddressDO::getUserId,currentUid);
        return Result.success(this.baseMapper.selectList(queryWrapper));
    }

    @Override
    public Result findDefault(Long currentUid) {
        LambdaQueryWrapper<UserReceiveAddressDO> queryWrapper = Wrappers.lambdaQuery(UserReceiveAddressDO.class)
                .eq(UserReceiveAddressDO::getIsDefault,true)
                .eq(UserReceiveAddressDO::getUserId,currentUid);
        return Result.success(this.baseMapper.selectOne(queryWrapper));
    }
}
